<script setup lang="ts">
import { ref, reactive, watch } from "vue"
import { ElMessage } from "element-plus"
import axios from "axios"
import provinceCityData from "province-city-china/data"
import { read } from '../../../stores/host'

const props = defineProps<{
    visible: boolean
    isEdit?: boolean
    customerData?: any
}>()

const emit = defineEmits<{
    (e: "update:visible", value: boolean): void;
    (e: "success"): void
}>()

// 省市数据
const provinceOptions = provinceCityData.province.map((province:any) => ({
    value: province.name,
    label: province.name,
    code: province.province,
}))

const cityOptions:any = ref([])

// 表单数据
const formData = reactive({
    id: "",
    customerCode: "",
    customerName: "",
    province: "",
    city: "",
    contactName: "",
})

// 表单校验规则
const rules = {
    customerName: [
        { required: true, message: "请输入客户名称", trigger: "blur" },
        { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
    ],
    province: [{ required: true, message: "请选择省份", trigger: "change" }],
    city: [{ required: true, message: "请选择城市", trigger: "change" }],
    contactName: [
        { required: true, message: "请输入联系人姓名", trigger: "blur" },
        { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
    ],
}

const formRef = ref()

// 生成客户编号
const generateCustomerCode = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, "0")
    const day = String(now.getDate()).padStart(2, "0")
    const hour = String(now.getHours()).padStart(2, "0")
    const minute = String(now.getMinutes()).padStart(2, "0")
    const second = String(now.getSeconds()).padStart(2, "0")
    const millisecond = String(now.getMilliseconds()).padStart(3, "0")
    const random = Math.floor(Math.random() * 100)
        .toString()
        .padStart(2, "0")

    return `KH${year}${month}${day}${hour}${minute}${second}${millisecond}${random}`
}

// 初始化表单
const initForm = () => {
    if (props.isEdit && props.customerData) {
        Object.assign(formData, {
            id: props.customerData.id,
            customerCode: props.customerData.customerCode,
            customerName: props.customerData.customerName,
            province: props.customerData.province,
            contactName: props.customerData.contactPerson,
        })
        // 先设置省份，生成城市选项
        handleProvinceChange(formData.province)
        // 再设置城市
        formData.city = props.customerData.city
    } else {
        Object.assign(formData, {
            id: "",
            customerCode: generateCustomerCode(),
            customerName: "",
            province: "",
            city: "",
            contactName: "",
        })
        cityOptions.value = []
    }
}

// 直辖市列表
const directCities = ["北京市", "上海市", "天津市", "重庆市"]

// 监听省份变化
const handleProvinceChange = (provinceName: string) => {
    formData.city = ""

    // 处理直辖市
    if (directCities.includes(provinceName)) {
        formData.city = provinceName
        cityOptions.value = [{ value: provinceName, label: provinceName }]
        return
    }

    const province = provinceCityData.province.find((p:any) => p.name === provinceName)
    if (province) {
        cityOptions.value = provinceCityData.city
            .filter((city:any) => city.province === province.province)
            .map((city:any) => ({
                value: city.name,
                label: city.name,
            }))
    } else {
        cityOptions.value = []
    }
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            try {
                const url = props.isEdit
                    ? "/salewrite/api/Customer/UpdateCustomer"
                    : "/salewrite/api/Customer/AddCustomer"
                const response = await (props.isEdit
                    ? read.put(url, formData)
                    : read.post(url, formData))

                if (response.data && response.data.code === 200) {
                    ElMessage.success(props.isEdit ? "修改客户成功" : "添加客户成功")
                    emit("success")
                    closeDialog()
                } else {
                    ElMessage.error(
                        response.data?.msg || (props.isEdit ? "修改客户失败" : "添加客户失败")
                    )
                }
            } catch (error) {
                console.error(props.isEdit ? "修改客户失败:" : "添加客户失败:", error)
                ElMessage.error(props.isEdit ? "修改客户失败" : "添加客户失败")
            }
        }
    })
}

// 关闭对话框
const closeDialog = () => {
    emit("update:visible", false)
}

// 监听对话框显示状态
watch(
    () => props.visible,
    (newVal) => {
        if (newVal) {
            initForm()
        }
    }
)
</script>

<template>
    <el-dialog :title="props.isEdit ? '修改客户' : '添加客户'" v-model="props.visible" width="500px" @close="closeDialog">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="客户编号" prop="customerCode">
                <el-input v-model="formData.customerCode" disabled placeholder="系统自动生成" />
            </el-form-item>

            <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
            </el-form-item>

            <el-form-item label="省份" prop="province">
                <el-select v-model="formData.province" placeholder="请选择省份" @change="handleProvinceChange"
                    style="width: 100%">
                    <el-option v-for="item in provinceOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="城市" prop="city">
                <el-select v-model="formData.city" placeholder="请选择城市"
                    :disabled="!formData.province || directCities.includes(formData.province)" style="width: 100%">
                    <el-option v-for="item in cityOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="联系人" prop="contactName">
                <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
    </el-dialog>
</template>
